var pinArray = [];
var source;
var width;
var height;
var isAddMode;
var isEditMode;
var imgCanvas;
var imgID;

function reInitCanvas() {
    initCanvas(imgCanvas, source, width, height, isAddMode, isEditMode);
    loadPins(imgID);
}

function initCanvas(imageCanvas, imageSource, imageWidth, imageHeight, isAdd) {
    initCanvas(imageCanvas, imageSource, imageWidth, imageHeight, isAdd, false);
}

function initCanvas(imageCanvas, imageSource, imageWidth, imageHeight, isAdd, isEdit) {
    isAddMode = isAdd;
    source = imageSource;
    width = imageWidth;
    height = imageHeight;
    isEditMode = isEdit;
    imgCanvas = imageCanvas;

    stage = new Kinetic.Stage({
        container: imgCanvas,
        width: parseInt(width) + 100,
        height: parseInt(height) + 100
    });
    imageLayer = new Kinetic.Layer();
    pinLayer = new Kinetic.Layer();
    labelLayer = new Kinetic.Layer();
    numberLayer = new Kinetic.Layer();

    var imageObj = new Image();
    imageObj.src = source;
    imageObj.onload = function() {
        var imageFile = new Kinetic.Image({
            x: 50,
            y: 50,
            image: imageObj,
            width: width,
            height: height
        });

        imageLayer.add(imageFile);
        stage.add(imageLayer);
        stage.add(labelLayer);
        stage.add(pinLayer);
        stage.add(numberLayer);

        imageFile.on('mouseup', function() {
            if (isAddMode) {
                getInput(0);
            } else if (isEditMode) {
                getInput(1);
            }
        });
    };
}

function getInput(mode) {
    // Add Mode = 0
    // Edit Mode = 1
    var mousePos = stage.getMousePosition();
    sessionStorage.setItem("posX", mousePos.x);
    sessionStorage.setItem("posY", mousePos.y);

    $('#pinInfo').val('');
    $('#pinCategory').prop('selectedIndex', 0);
    $('#pinTags').val('');

    if (mode === 0) {
        $('#addPinModal').modal('show');
    } else if (mode === 1) {
        $('#addPinEditModal').modal('show');
        setTimeout(function() {
            $('#addPinEditModal').modal('hide');
        }, 50);
        setTimeout(function() {
            $('#addPinEditModal').modal('show');
        }, 100);
        $('#addPinEditX').val(mousePos.x);
        $('#addPinEditY').val(mousePos.y);
    }
}

function addPin(pinInfo, pinCategory, pinTagsArray, posX, posY, isLiked, pinID) {
    var star = new Kinetic.Circle({
        x: posX,
        y: posY,
        radius: 8,
        stroke: 'white',
        strokeWidth: 2,
        fill: isLiked ? 'red' : 'green',
        opacity: 0.7
    });

    pinLayer.add(star);
    pinLayer.draw();

    var newPin = {
        "star": star,
        "pinInfo": pinInfo,
        "pinCategory": pinCategory,
        "pinTagsArray": pinTagsArray,
        "posX": posX,
        "posY": posY,
        "pinID": pinID};

    pinArray.push(newPin);
    storeDataToSession();

    star.on('mouseover', function() {
        pinMouseOver(star);
    });

    star.on('mouseup', function() {

        if (isAddMode) {
            for (var i = 0; i < pinArray.length; i++) {
                if (pinArray[i].star === star) {
                    pinArray.pop(i);
                    storeDataToSession();
                }
            }
            star.destroy();
            pinLayer.draw();
        } else if (isEditMode) {
            loadEditModal(star);
        } else {
            loadViewModal(star);
        }
    });

    if (!isAddMode) {
        $.ajax({
            type: 'POST',
            url: '/LifeBook/GetPinLikesServlet',
            data: {
                pinID: pinID
            },
            success: function(msg) {
                var result = eval("(" + msg + ")");
                var pinLikes = new Kinetic.Text({
                    x: posX - 3,
                    y: posY - 6,
                    text: result.pinlikes,
                    fontSize: 12,
                    fontFamily: 'Calibri',
                    fill: 'white',
                    drawHitFunc: function(canvas) {
                        var context = canvas.getContext();
                        context.beginPath();
                        context.arc(0, 0, 0, 0, 0, true);
                        context.closePath();
                        canvas.fillStroke(this);
                    }
                });

                numberLayer.add(pinLikes);
                numberLayer.draw();
            }
        });
    }
}

function addNewPin(addPinEditInfo, addPinEditCategory, addPinEditTags, xVal, yVal) {
    $.ajax({
        type: 'POST',
        url: '/LifeBook/AddPinEditModeServlet',
        data: {
            pinInfo: addPinEditInfo,
            pinCategory: addPinEditCategory,
            pinTags: addPinEditTags,
            x: Math.floor(xVal),
            y: Math.floor(yVal),
            imageID: imgID
        },
        success: function(msg) {
            var result = eval("(" + msg + ")");
            $('#addPinEditModal').modal('hide');
            reInitCanvas();
        }
    });
}

function loadEditModal(star) {
    for (var i = 0; i < pinArray.length; i++) {
        if (pinArray[i].star === star) {
            $('#editPinID').val(pinArray[i].pinID);
            $('#editPinInfo').val(pinArray[i].pinInfo);
            $('#editPinCategory').val(pinArray[i].pinCategory);
            var tagsString = '';
            for (j = 0; j < pinArray[i].pinTagsArray.length; j++) {
                tagsString += pinArray[i].pinTagsArray[j] + ',';
            }
            $('#editPinTag').val(tagsString);

            $.ajax({
                type: 'POST',
                url: '/LifeBook/GetPinLikesServlet',
                data: {
                    pinID: pinArray[i].pinID
                },
                success: function(msg) {
                    var result = eval("(" + msg + ")");

                    if (result.isLiked) {
                        $('#editPinLikeIcon').addClass("icon-white");
                        $('#editPinLikeButton').addClass("btn-danger");
                        $('#editPinLikeButton').addClass("active");
                    } else {
                        $('#editPinLikeIcon').removeClass("icon-white");
                        $('#editPinLikeButton').removeClass("btn-danger");
                        $('#editPinLikeButton').removeClass("active");
                    }
                    $('#editPinLikeCounter').html(result.pinlikes);

                    $('#editPinModal').modal('show');
                    setTimeout(function() {
                        $('#editPinModal').modal('hide');
                    }, 50);
                    setTimeout(function() {
                        $('#editPinModal').modal('show');
                    }, 100);
                }
            });
        }
    }
}

function editLikePin(id) {
    $.ajax({
        type: 'POST',
        url: '/LifeBook/UserLikesAPinServlet',
        data: {
            pinID: id
        },
        success: function(msg) {
            var result = eval("(" + msg + ")");

            $.ajax({
                type: 'POST',
                url: '/LifeBook/GetPinLikesServlet',
                data: {
                    pinID: id
                },
                success: function(msg) {
                    var result = eval("(" + msg + ")");

                    if (result.isLiked) {
                        $('#editPinLikeIcon').addClass("icon-white");
                        $('#editPinLikeButton').addClass("btn-danger");
                        $('#editPinLikeButton').addClass("active");
                    } else {
                        $('#editPinLikeIcon').removeClass("icon-white");
                        $('#editPinLikeButton').removeClass("btn-danger");
                        $('#editPinLikeButton').removeClass("active");
                    }
                    $('#editPinLikeCounter').html(result.pinlikes);
                    reInitCanvas();
                }
            });
        }
    });
}

function viewLikePin(id) {
    $.ajax({
        type: 'POST',
        url: '/LifeBook/UserLikesAPinServlet',
        data: {
            pinID: id
        },
        success: function(msg) {
            var result = eval("(" + msg + ")");

            $.ajax({
                type: 'POST',
                url: '/LifeBook/GetPinLikesServlet',
                data: {
                    pinID: id
                },
                success: function(msg) {
                    var result = eval("(" + msg + ")");

                    if (result.isLiked) {
                        $('#viewPinLikeIcon').addClass("icon-white");
                        $('#viewPinLikeButton').addClass("btn-danger");
                        $('#viewPinLikeButton').addClass("active");
                    } else {
                        $('#viewPinLikeIcon').removeClass("icon-white");
                        $('#viewPinLikeButton').removeClass("btn-danger");
                        $('#viewPinLikeButton').removeClass("active");
                    }
                    $('#viewPinLikeCounter').html(result.pinlikes);
                    reInitCanvas();
                }
            });
        }
    });
}

function loadViewModal(star) {
    for (var i = 0; i < pinArray.length; i++) {
        if (pinArray[i].star === star) {
            $('#viewPinID').val(pinArray[i].pinID);
            $('#viewPinInfo').html(pinArray[i].pinInfo);
            $('#viewPinCategory').html(pinArray[i].pinCategory);
            var tagsString = '';
            for (j = 0; j < pinArray[i].pinTagsArray.length; j++) {
                tagsString += pinArray[i].pinTagsArray[j] + ',';
            }
            $('#viewPinTags').html(tagsString);

            $.ajax({
                type: 'POST',
                url: '/LifeBook/GetPinLikesServlet',
                data: {
                    pinID: pinArray[i].pinID
                },
                success: function(msg) {
                    var result = eval("(" + msg + ")");

                    if (result.isLiked) {
                        $('#viewPinLikeIcon').addClass("icon-white");
                        $('#viewPinLikeButton').addClass("btn-danger");
                        $('#viewPinLikeButton').addClass("active");
                    } else {
                        $('#viewPinLikeIcon').removeClass("icon-white");
                        $('#viewPinLikeButton').removeClass("btn-danger");
                        $('#viewPinLikeButton').removeClass("active");
                    }
                    $('#viewPinLikeCounter').html(result.pinlikes);

                    $('#viewPinModal').modal('show');
                    setTimeout(function() {
                        $('#viewPinModal').modal('hide');
                    }, 50);
                    setTimeout(function() {
                        $('#viewPinModal').modal('show');
                    }, 100);
                }
            });
        }
    }
}

function confirmEdit(editPinInfo, editPinCategory, editPinTag, editPinID) {
    $.ajax({
        type: 'POST',
        url: '/LifeBook/EditPinServlet',
        data: {
            pinInfo: editPinInfo,
            pinCategory: editPinCategory,
            pinTags: editPinTag,
            pinID: editPinID
        },
        success: function(msg) {
            var result = eval("(" + msg + ")");
            $('#editPinModal').modal('hide');
            reInitCanvas();
        }
    });
}

function pinMouseOver(star) {
    for (var i = 0; i < pinArray.length; i++) {
        if (pinArray[i].star === star) {
            $('#pinPopOver').css({
                left: pinArray[i].posX,
                top: pinArray[i].posY
            });

            // simple label
            var labelX = pinArray[i].posX > Math.floor(width / 2) ?
                    (parseInt(pinArray[i].posX) - 120) :
                    (parseInt(pinArray[i].posX) + 30);
            var labelY = pinArray[i].posY > Math.floor(height / 2) ?
                    (parseInt(pinArray[i].posY) - 180) :
                    (parseInt(pinArray[i].posY) + 10);
            var pinLabel = new Kinetic.Label({
                x: labelX,
                y: labelY,
                opacity: 0.80
            });

            pinLabel.add(new Kinetic.Tag({
                fill: 'white',
                stroke:'black'
            }));

            pinLabel.add(new Kinetic.Text({
                text: pinDataToLabel(pinArray[i]),
                fontFamily: 'Calibri',
                fontSize: 18,
                padding: 5,
                fill: 'black'
            }));

            labelLayer.add(pinLabel);
            labelLayer.draw();

            star.on('mouseout', function() {
                pinLabel.destroy();
                labelLayer.draw();
            });
        }
    }
}

function pinDataToLabel(pinData) {
    var result = new String("");

    result = result.concat("Pin Info:\n");
    result = result.concat(pinData.pinInfo + "\n\n");

    result = result.concat("Category:\n");
    result = result.concat(pinData.pinCategory + "\n\n");

    result = result.concat("Tags:\n");
    result = result.concat("|");
    for (i = 0; i < pinData.pinTagsArray.length; i++) {
        if (pinData.pinTagsArray[i] !== null)
            result = result.concat(pinData.pinTagsArray[i]);

        result = result.concat(" | ");

        if (i % 2) {
            result = result.concat("\n");
            if (i < (pinData.pinTagsArray.length - 1))
                result = result.concat("|");
        }
    }
    return result;
}

function storeDataToSession() {
    sessionStorage.setItem("pinData", JSON.stringify(pinArray));
}
function loadPins(imageID) {
    imgID = imageID;
    $.ajax({
        type: 'POST',
        url: '/LifeBook/LoadPinsServlet',
        data: {
            imageID: imageID
        },
        success: function(msg) {
            var resultPinArray = eval("(" + msg + ")");
            pinArray = new Array();
            for (var i = 0; i < resultPinArray.length; i++) {
                addPin(resultPinArray[i].pinInfo, resultPinArray[i].pinCategory, resultPinArray[i].pinTagsArray,
                        resultPinArray[i].x, resultPinArray[i].y, resultPinArray[i].pinIsLikedByUser, resultPinArray[i].pinID);
            }
        }
    });
}
function likePin(star) {
    var pinID;
    for (var i = 0; i < pinArray.length; i++) {
        if (pinArray[i].star === star) {
            pinID = pinArray[i].pinID;
        }
    }
    $.ajax({
        type: 'POST',
        url: '/LifeBook/UserLikesAPinServlet',
        data: {
            pinID: pinID
        },
        success: function(msg) {
            var result = eval("(" + msg + ")");
            if (result.pinIsLikedByUser) {
                star.setAttr('fill', 'red');
            } else {
                star.setAttr('fill', 'green');
            }
            pinLayer.draw();
        }
    });

}

function deletePin(pinID) {
    $.ajax({
        type: 'POST',
        url: '/LifeBook/DeletePinServlet',
        data: {
            pinID: pinID
        },
        success: function(msg) {
            var result = eval("(" + msg + ")");
            reInitCanvas();
        }
    });
}

function browseRelatedPins(category, tags) {
    window.location = '/LifeBook/BrowseRelatedPinsServlet?category=' + category + '&tags=' + tags;
}